using System.Configuration;
using Aluetjen.EmailService.Domain.Infrastructure;
using Aluetjen.EmailService.Infrastructure.Persistence;
using Aluetjen.EmailService.Infrastructure.Registries;
using NHibernate;
using StructureMap;
using StructureMap.Pipeline;
using log4net;

namespace Aluetjen.EmailService.Infrastructure
{
    public static class IoC
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof (IoC));

        public static IContainer Initialize()
        {
            var connectionStringFromConfig = ConfigurationManager.ConnectionStrings["EmailService"];
            
            if(connectionStringFromConfig == null)
            {
                Log.InfoFormat("No database connection configured. Defaulting to database 'EmailService' on local host.");

                connectionStringFromConfig = new ConnectionStringSettings("EmailService", "Data source=.;Initial catalog=EmailService;Integrated security=true;");
            }
            
            var helper = new NHibernateHelper(connectionStringFromConfig.ConnectionString);

            ObjectFactory.Initialize(x =>
                                         {
                                             x.Scan(scan =>
                                                        {
                                                            scan.TheCallingAssembly();
                                                            scan.WithDefaultConventions();
                                                        });

                                             x.For<ISessionFactory>().Singleton().Use(ctx => helper.SessionFactory);
                                             x.For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<NHibernateUnitOfWork>();
                                             x.For<ISession>().Use(ctx => (ctx.GetInstance<IUnitOfWork>() as NHibernateUnitOfWork).Session);
                                             
                                             x.For(typeof(IRepository<>)).Use(typeof(NHibernateRepository<>));
                                             
                                             x.AddRegistry(new GatewayRegistry());
                                             x.AddRegistry(new ServiceRegistry());
                                         });

            ObjectFactory.AssertConfigurationIsValid();
            new HybridLifecycle().FindCache().DisposeAndClear();

            return ObjectFactory.Container;
        }

        public static IContainer Container
        {
            get { return ObjectFactory.Container; }
        }
    }
}